package com.orcsystem.member.controller;
import com.orcsystem.common.exception.BizCodeEnume;
import com.orcsystem.common.utils.PageUtils;
import com.orcsystem.common.utils.R;
import com.orcsystem.member.entity.MemberEntity;
import com.orcsystem.member.exception.MobileExistException;
import com.orcsystem.member.exception.UserNameExistException;
import com.orcsystem.member.service.MemberService;
import com.orcsystem.member.vo.MemberLoginVo;
import com.orcsystem.member.vo.MemberRegistVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Map;



/**
 * 会员
 *
 * @author aihs
 * @email aihs_work@163.com
 * @date 2020-06-01 14:23:29
 */
@RestController
@RequestMapping("member/member")
public class MemberController {
    @Autowired
    private MemberService memberService;

    @Transactional
    @PostMapping("/regist")
    public R regist(@RequestBody MemberRegistVo vo){
        try {
            memberService.regist(vo);
        }catch (MobileExistException e){
            // 手机号已存在
            return R.error(BizCodeEnume.MOBILE_EXIST_EXCEPTION.getCode(),BizCodeEnume.MOBILE_EXIST_EXCEPTION.getMsg());
        }catch (UserNameExistException e){
            // 用户名已存在
            return R.error(BizCodeEnume.USER_EXIST_EXCEPTION.getCode(),BizCodeEnume.USER_EXIST_EXCEPTION.getMsg());
        }
        return R.ok();
    }

    @PostMapping("/login")
    public R login(@RequestBody MemberLoginVo vo){
        MemberEntity member = memberService.login(vo);
        if (member == null){
            // 返回错误消息
            int code = BizCodeEnume.PASSWORD_EXIST_EXCEPTION.getCode();
            String mes = BizCodeEnume.PASSWORD_EXIST_EXCEPTION.getMsg();
            new R().error();
            return R.error(code,mes);
        }
        return R.ok();
    }
    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = memberService.queryPage(params);
        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Long id){
		MemberEntity member = memberService.getById(id);
        return R.ok().put("member", member);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody MemberEntity member){
		memberService.save(member);
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody MemberEntity member){
		memberService.updateById(member);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] ids){
		memberService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

}
